package com.scanner.barcodeservice;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.IBinder;

import com.scanner.util.LogUtil;
import com.scanner.util.SharePreConfig;

public class ScannerPortService extends Service {
    public static final String BARCODEPORT_RECEIVED_ACTION = "com.android.barcodeservice.RECER_ACTION";//发送广播
    public static final String BARCODEPORT_RECEIVEDDATA_EXTRA_DATA = "get_data";//得到数据
    public static final String BARCODEPORT_WRITEDATA_ACTION = "com.android.barcodeservice.WRITE_DATA";//写数据广播
    private SerialPortManager serialPortManager;
    private WriteDataToPortAsyncTask writeDataToPortAsyncTask;
    public ScannerPortService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int baudRate = SharePreConfig.getBaudRate();
        openUart(baudRate);
        serialPortManager.read();//串口读取监听
        serialPortManager.setListener(mSerialPortListener);
        register();
        return START_STICKY;
    }



    private byte[] openQR = new byte[]{0x08, (byte) 0xC6,04,0x00, (byte) 0xFF, (byte) 0xF0,0x25,0x01, (byte) 0xFD,0x19};
    private byte[]  closeQR = new byte[] {0x08, (byte) 0xC6,0x04,0x00, (byte) 0xFF, (byte) 0xF0,0x25,0x00, (byte) 0xFD,0x1A};
    /**
     * 打开串口
     * @param mbaudrate
     * @param
     */
    public void openUart(int mbaudrate){
        LogUtil.i("串口打开方法openUart=="+mbaudrate);
        serialPortManager = SerialPortManager.getInstance();
        serialPortManager.open(mbaudrate);//打开串口
		serialPortManager.writeMoto(openQR);
    }

    SerialPortManager.SerialPortListener mSerialPortListener = new SerialPortManager.SerialPortListener() {

        @SuppressLint("NewApi")
        @Override
        public void onResult(String data) {
            String temp = byte2hex(data.getBytes());
            LogUtil.e("串口监听到数据temp="+temp);
            LogUtil.e("串口监听到数据data="+data);
            String edit_data = data + "\t";

            Intent intent=new Intent(BARCODEPORT_RECEIVED_ACTION);
            intent.putExtra(BARCODEPORT_RECEIVEDDATA_EXTRA_DATA, edit_data);
            getApplicationContext().sendBroadcast(intent);
        }
    };

    private void register(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BARCODEPORT_WRITEDATA_ACTION);//barcode串口写入数据
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(receiver, intentFilter);
    }


    /**
     * Broadcast receiver.
     * */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            LogUtil.e("广播action=="+action);
            if(action!=null){
                if(action.equals(BARCODEPORT_WRITEDATA_ACTION)){
                    String dataHex=intent.getStringExtra(BARCODEPORT_WRITEDATA_ACTION);
                    if(dataHex!=null){
                        LogUtil.e("广播获取到数据=="+dataHex);
                        writeDataToPortAsyncTask = new WriteDataToPortAsyncTask();
                        writeDataToPortAsyncTask.execute(dataHex);

                    }
                }
            }
        }
    };



    /**
     * Write data task
     * */
    private class WriteDataToPortAsyncTask extends AsyncTask<String, Integer, Integer> {

        @Override
        protected Integer doInBackground(String... params) {
            int res=0;
            String data=params!=null&&params.length>0?params[0]:null;
            res = serialPortManager.write(data);
            LogUtil.i("串口写入数据"+res);
            return res;
        }
    }

    private String byte2hex(byte [] buffer){
        String h = "";
        for(int i = 0; i < buffer.length; i++){
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if(temp.length() == 1){
                temp = "0" + temp;
            }
            h = h + " "+ temp;
        }

        return h;
    }
}
